package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


import com.lastproject.dto.DepartmentDTO;

import com.lastproject.ejb.entities.Department;
import com.lastproject.ejb.util.DepartmentConversion;

/**
 * Session Bean implementation class DepartmentDAO
 */
@Stateless
public class DepartmentDAO implements DepartmentDAORemote {

	@PersistenceContext
	EntityManager em;

	@EJB
	DepartmentConversion conv;

    /**
     * Default constructor. 
     */
    public DepartmentDAO() {
        // TODO Auto-generated constructor stub
    }

    
    @Override
   	public void create(DepartmentDTO departmentDTO) {
   		// TODO Auto-generated method stub
   		em.persist(conv.fromDTO(departmentDTO));
   	}
    
    @Override
	public void edit(DepartmentDTO departmentDTO) {
		// TODO Auto-generated method stub
		em.merge(conv.fromDTO(departmentDTO));
	}

	@Override
	public void remove(DepartmentDTO departmentDTO) {
		// TODO Auto-generated method stub
		em.remove(em.merge(conv.fromDTO(departmentDTO)));
	}
	
	@Override
	public DepartmentDTO findById(int id) {
		// TODO Auto-generated method stub
		Department department = new Department();

		department = em.find(Department.class, id);

		return conv.fromEntity(department);
	}
	
	@Override
	public List<DepartmentDTO> getAll() {
		// TODO Auto-generated method stub
		List<Department> departmentList = new ArrayList<Department>();

		departmentList = em.createNamedQuery("Department.findAll", Department.class)
				.getResultList();

		List<DepartmentDTO> dDTOList = new ArrayList<DepartmentDTO>();

		for (Department d : departmentList) {
			dDTOList.add(conv.fromEntity(d));
		}

		return dDTOList;
	}
}
